package com.hongfeng.support.intercepter.impl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hongfeng.support.annotation.Online;
import com.hongfeng.support.common.Constants;
import com.hongfeng.support.intercepter.UnlineInvocation;
import com.hongfeng.support.model.User;
import com.hongfeng.support.util.WebHelper;

public class UnlineInvocationInterceptor extends HandlerInterceptorAdapter implements UnlineInvocation {

	protected Log logger = LogFactory.getLog(this.getClass());

	/**
	 * 请求后缀，比如：“.do”、“.action”等，默认为 ：“.jsps”。
	 */
	@Override
	public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("UnlineInvocationInterceptor preHandle");
		Online online = handler.getClass().getAnnotation(Online.class);
		User user = WebHelper.getSessionAttribute(request, Constants.SESSION_LOGIN_USER);
		boolean intercepted = online != null && user == null;
		if (intercepted) {
			this.invok(request, response, online);
		}
		return !intercepted;
	}

	public void invok(HttpServletRequest request, HttpServletResponse response, Online online) {
		String ctx = request.getContextPath();
		String refer = request.getHeader("Referer");
		logger.info("ctx = " + ctx);
		logger.info("refer = " + refer);
		try {
			if (refer == null) {
				response.sendRedirect(ctx + "/login.html");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
